<?php

use think\facade\Config;
use think\facade\Log;


class Payoneer
{
    protected $config;
    protected $authorization;   //HTTP Authorization Scheme
	protected $_httpCode=0;		//response返回的http code
	protected $_errorMsg;
    
    public function __construct()
    {
        $this->config       = Config::get('payoneer');
        $this->authorization= 'Basic '.base64_encode($this->config['api_username'].':'.$this->config['token']);
    }

    /**
     * 创建新支付会话
     * 接口：api/lists
     * 
     * @param float $amount  订单金额
     * @param array $order 订单信息
     * @param string $country 发起付款的国家/地区
     * 
     * @return array $result
     * 
     */
    public function createPayment($amount,$order,$country='US')
    {
        //返回值
        $result = [ 
			"code" 	=> 500,
			"msg" 	=> "",
		];

        //回调验签参数,根据您实际需要设置规则
        $token = 'xxxxxxxxxxx';

         // Initialize Payoneer payment
         $paymentData = [
            'integration'   =>'SELECTIVE_NATIVE',             //嵌入式集成场景
            'transactionId' =>$order['order_code'],
            'country'       =>$country,
            'division'      =>$this->config['division'],               //在 Checkout 收单服务中，这是在您的 Payoneer 账户门户的集成页面上显示的店铺代码
            'callback'      =>['returnUrl'          =>request()->domain().'/paysuccess?order_code='.$order['order_code'],
                                'cancelUrl'         =>request()->domain().'/payment?order_code='.$order['order_code'],
                                'notificationUrl'   =>request()->domain().'/pay/payoneerNotification?token='.$token                  //系统将向此 URL 发送有关此付款的非同步状态通知
                                ],
            'customer'      =>['addresses'=>['shipping'=>['street'   =>mb_substr($order['street'], 0, 80,"UTF-8"),
                                                         'zip'      =>$order['zip'],
                                                         'city'     =>mb_substr($order['city'], 0, 80,"UTF-8"),
                                                         'state'    =>mb_substr($order['state'], 0, 80,"UTF-8"),
                                                         'country'  =>$order['country']
                                                ],
											//账单地址
                                            'billing'=>['street'   =>mb_substr($order['street'], 0, 80,"UTF-8"),
                                                         'zip'      =>$order['zip'],
                                                         'city'     =>mb_substr($order['city'], 0, 80,"UTF-8"),
                                                         'state'    =>mb_substr($order['state'], 0, 80,"UTF-8"),
                                                         'country'  =>$order['country']
                                                ]
                            ],
                            'email' =>$order['email'],
            ],
            'payment'       =>['amount'     =>$amount,
                                'currency'  =>'USD',
                                'reference' =>'Short description'
                            ],
            'products'       =>[['amount'   =>$amount,
                                'name'      =>'您产品的名称',
                            ]],
            'ttl'           =>5     //[5分钟过期]Time to live (TTL) for LIST session in minutes. By default LIST session is valid for 30 min.
        ];

        $url = $this->config['endpoint'].'/api/lists';

        $param = json_encode($paymentData);

        $header = ['Authorization'	=> $this->authorization,
                    'content-type'	=> 'application/json'
        ];
        
        Log::info('payoneer api/lists：param='.$param);
		
		$response = $this->request($url,$param,'POST',0,$header);
  
        if($this->_httpCode=='200'){

            Log::info('payoneer api/lists接口成功：'.$response;

            $re = json_decode($response,true);

            $result['code'] = 200;
            $result['data'] = $re;
        }
        else{
            Log::error("payoneer api/lists接口请求失败";

            $re = json_decode($response,true);

            $result['msg'] = isset($re['resultInfo']) ? $re['resultInfo'] : "Requesting Payoneer's interface failed";
        }

        return $result;
    }
	
	
	private function request($url, $params=null, $method = 'GET', $returnHeader = 0,$headers=null)
    {
        $ci = curl_init();
        //curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ci, CURLOPT_HEADER, $returnHeader);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLOPT_TIMEOUT, 20);

        if($this->_auth){
            curl_setopt($ci, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ci, CURLOPT_USERPWD, $this->_auth);
        }

        $ifSSL = strpos($url,"https://");
        if($ifSSL !==false){
            curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);        //不验证 SSL 对等证书
        }

        switch ($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, TRUE);
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params); 
                break;
            case 'PUT':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            case 'PATCH':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, "PATCH");
                curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
                break;
            case 'DELETE':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
            case 'OPTION':
                curl_setopt($ci, CURLOPT_CUSTOMREQUEST, "OPTION");
                break;
            case 'GET':
                if($params){
                    $url.=strpos($url,'?')===false?'?':'&';
                    $url.= is_array($params)?http_build_query($params):$params;
                }
                break;
        }
        
        curl_setopt($ci, CURLOPT_URL, $url);
        //当需要通过curl_getinfo来获取发出请求的header信息时，该选项需要设置为true
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);

        $response = curl_exec($ci);

        if (FALSE === $response) {

            $this->_errorMsg = "request url '{$url}' error. ". curl_error($ci);         
        }
        else{
			$this->_httpCode = curl_getinfo($ci, CURLINFO_HTTP_CODE);
        }
        
        curl_close($ci);
        return $response;
    }
}
